<template>
  <div class="suggest">
    <h2>客户反馈分析</h2>
    <div class="search-container">
      <el-input class="el-input" v-model="searchQuery" placeholder="输入用户id / 姓名搜索"
        @keyup.enter="searchUsers"></el-input>
      <el-button class="el-button" @click="searchUsers">
        <img src="../../assets/img/search.png" alt="">
        筛选
      </el-button>
      <!-- 删除按钮 -->
      <el-button class="el-button remove" @click="deleteSelectedUsers" :disabled="selectedUsers.length === 0">
        删除
      </el-button>
      <el-table :data="currentUsers" stripe ref="userTable" @selection-change="handleTableSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="UserId" label="用户Id"></el-table-column>
        <el-table-column label="用户信息" width="150">
          <template slot-scope="scope">
            <p style="margin-left: 5px;">{{ scope.row.UserName }}</p>
            <p style="margin-left: 5px">{{ scope.row.Phone }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="Suggest" label="反馈类型"></el-table-column>
        <el-table-column prop="SugMessage" label="反馈内容" width="200"></el-table-column>
        <el-table-column prop="SugTime" label="提交时间"  width="200">
          <template slot-scope="scope">
            <span>
              {{ formatTime(scope.row.SugTime) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="State" label="用户状态">
          <template slot-scope="scope">
            <div>
              {{ scope.row.State }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <p style="color: blue;cursor: pointer;" @click="showDetailDialog(scope.row)">查看详情</p>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[10, 20, 30]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="totalUsers">
      </el-pagination>
    </div>

    <!-- 查看详情弹窗 -->
    <el-dialog :visible.sync="dialogVisible" title="反馈详情">
      <div class="detail-content">
        <div class="detail-row">
          <div class="detail-item">
            <p class="detail-label">反馈编号</p>
            <p>{{ detail.UserId }}</p>
          </div>
          <div class="detail-item">
            <p class="detail-label">提交时间</p>
            <p>{{ detail.SugMessage }}</p>
          </div>
        </div>
        <div class="detail-row">
          <div class="detail-item">
            <p class="detail-label">用户姓名</p>
            <p>{{ detail.UserName }}</p>
          </div>
          <div class="detail-item">
            <p class="detail-label">联系方式</p>
            <p>{{ detail.Phone }}</p>
          </div>
        </div>
        <div class="detail-row">
          <div class="detail-item">
            <p class="detail-label">反馈类型</p>
            <p>{{ detail.Suggest }}</p>
          </div>
        </div>
        <div class="detail-item">
          <p class="detail-label">反馈内容</p>
          <p>{{ detail.SugMessage }}</p>
        </div>

        <div>
          <label class="detail-label" style="margin-top: 20px;">添加处理备注：</label>
          <div class="detail-row detail-SugMessage">
            <el-input v-model="remark" placeholder="请输入处理备注"></el-input>
            <el-button @click="sendRemark" class="send-button" style="margin-left: 10px;">发送</el-button>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" class="close-button">关闭</el-button>
        <el-button @click="confirm" class="confirm-button">确认</el-button>
      </span>
    </el-dialog>

    <!-- 删除确认提示框 -->
    <el-dialog :visible.sync="deleteDialogVisible" title="删除用户" width="350px">
      <p>确定要删除用户（{{ deleteUserNames.join(', ') }}）吗？此操作不可恢复</p>
      <span class="dialog-footer" style="margin-top: 20px;display: block;">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmDelete">确定</el-button>
      </span>
    </el-dialog>


    <div class="stats-container">
      <div class="stat-item">
        <h3>反馈类型分布</h3>
        <div id="feedback-type-chart" style="width: 100%; height: 300px;"></div>
      </div>
      <div class="stat-item">
        <h3>处理时效分析</h3>
        <div id="processing-time-chart" style="width: 100%; height: 300px;"></div>
      </div>
    </div>
    <div class="stats-container">
      <div class="stat-item-1">
        <h3>本月反馈总量</h3>
        <p class="stat-value">{{ feedbackTotal }}</p>
        <p :class="growthRate > 0 ? 'increase' : 'decrease'"><i class="el-icon-arrow-up"></i> 较上月增长 {{ growthRate }}%
        </p>
      </div>
      <div class="stat-item-1">
        <h3>平均处理时长</h3>
        <p class="stat-value">{{ averageTime }}h</p>
        <p :class="reduceTime > 0 ? 'decrease' : 'increase'"><i class="el-icon-arrow-down"></i> 较上月减少 {{ reduceTime }}h
        </p>
      </div>
      <div class="stat-item-1">
        <h3>待处理反馈</h3>
        <p class="stat-value">{{ pendingFeedback }}</p>
        <p class="stat-tip">需要及时处理</p>
      </div>
      <div class="stat-item-1">
        <h3>用户满意度</h3>
        <p class="stat-value">{{ satisfactionRate }}%</p>
        <p :class="improvementRate > 0 ? 'increase' : 'decrease'"><i class="el-icon-arrow-up"></i> 较上月提升 {{
          improvementRate
        }}%</p>
      </div>
    </div>
  </div>
</template>

<script>
import { SugMessage } from 'element-ui';
import * as echarts from 'echarts';
import jq from "jquery"
export default {
  data() {
    return {
      users: [],
      searchQuery: '',
      currentPage: 1,
      pageSize: 10,
      totalUsers: 0,
      selectedUsers: [],
      detail: {},
      deleteDialogVisible: false, // 控制删除确认弹窗显示隐藏
      deleteUserNames: [], // 存储要删除的用户姓名
      dialogVisible: false,
      remark: '',
      feedbackTotal: 156,
      growthRate: 12,
      averageTime: 2.5,
      reduceTime: 0.5,
      pendingFeedback: 23,
      satisfactionRate: 92,
      improvementRate: 3,
      // 图表数据
      feedbackTypeData: [
        { value: 30, name: '商品相关' },
        { value: 25, name: '物流相关' },
        { value: 40, name: '售后服务' },
        { value: 15, name: '系统建议' },
        { value: 46, name: '其他' }
      ],
      processingTimeData: [
        { name: '周一', value: 2.5 },
        { name: '周二', value: 2 },
        { name: '周三', value: 3.2 },
        { name: '周四', value: 2.8 },
        { name: '周五', value: 2.2 },
        { name: '周六', value: 2.4 },
        { name: '周日', value: 2.8 }
      ]

    };
  },
  mounted() {
    this.initFeedbackTypeChart();
    this.initProcessingTimeChart();
    this.getData();
  },
  computed: {
  currentUsers() {
    const start = (this.currentPage - 1) * this.pageSize;
    const end = start + this.pageSize;
    const filteredUsers = this.users.filter(user => {
      // ：处理 UserName 为 null/undefined 的情况，转为空字符串
      const userName = user.UserName || ''; 
      const searchMatched = userName.includes(this.searchQuery); // 现在一定是字符串调用 includes
      const suggestValid = user.Suggest != null && user.Suggest.toString().trim() !== '';
      return suggestValid && searchMatched;
    });
    return filteredUsers.slice(start, end);
  }
},
  methods: {
    formatTime(timeStr) {
      if (!timeStr) return '';
      const date = new Date(timeStr);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },
    getData() {
      let _this = this
      jq.ajax({
        type: "get",
        url: "http://127.0.0.1:3000/usermess",
        data: {
          value: this.add
        },
        success(res) {
          console.log('res', res)
          if (res.data == "") {
            return
          } else {
            _this.users = res.data
            console.log('_this.users', _this.users)
          }

        }
      })
    },
    sendRemark() {
      // 这里可以添加发送备注的逻辑，例如调用API
      console.log('发送处理备注:', this.remark);
      // 模拟发送成功，实际中应根据API返回结果判断
      SugMessage.success('发送成功');
      this.remark = '';
    },
    searchUsers() {
      this.currentPage = 1;
      const filteredUsers = this.users.filter(user =>
        user.UserName.includes(this.searchQuery)
      );
      console.log('过滤后的用户数据：', filteredUsers);
      this.totalUsers = filteredUsers.length;
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      const filteredUsers = this.users.filter(user =>
        user.UserName.includes(this.searchQuery)
      );
      this.totalUsers = filteredUsers.length;
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      const filteredUsers = this.users.filter(user =>
        user.UserName.includes(this.searchQuery)
      );
      this.totalUsers = filteredUsers.length;
    },
    // 处理表格选中项变化
    handleTableSelectionChange(selection) {
      this.selectedUsers = selection;
      this.deleteUserNames = selection.map(user => user.UserName);
    },
    showDetailDialog(row) {
      console.log("查看详情点击成功");
      // 确保row有值
      if (row) {
        this.detail = row;
        this.dialogVisible = true;
      } else {
        console.error('传递的行数据row未定义');
      }
    },
    // 打开删除确认弹窗
    deleteSelectedUsers() {
      // console.log("删除确认弹窗点击成功");
      this.deleteDialogVisible = true;
    },
    // 确认删除操作
    confirmDelete() {
      this.users = this.users.filter(user => {
        return !this.selectedUsers.some(selectedUser => selectedUser.UserId === user.UserId);
      });
      this.selectedUsers = [];
      this.deleteUserNames = [];
      this.deleteDialogVisible = false;
      SugMessage.success('删除成功');
      // 更新总用户数和当前页码
      this.totalUsers = this.users.length;
      this.currentPage = 1;
    },
    confirm() {
      // 这里可以添加确认操作的逻辑，例如调用API保存反馈状态等
      console.log('点击了确认按钮，当前反馈状态：', this.detail.State);
      // 假设调用API成功后关闭弹窗
      this.dialogVisible = false;
    },
    initFeedbackTypeChart() {
      const chartDom = document.getElementById('feedback-type-chart');
      const myChart = echarts.init(chartDom);
      const option = {
        series: [
          {
            type: 'pie',
            radius: ['40%', '70%'],
            data: this.feedbackTypeData,
            label: {
              formatter: '{b}: {c}'
            }
          }
        ]
      };
      myChart.setOption(option);
    },
    initProcessingTimeChart() {
      const chartDom = document.getElementById('processing-time-chart');
      const myChart = echarts.init(chartDom);
      const option = {
        xAxis: {
          type: 'category',
          data: this.processingTimeData.map(item => item.name)
        },
        yAxis: {
          type: 'value',
          name: '平均处理时长(小时)'
        },
        series: [
          {
            data: this.processingTimeData.map(item => item.value),
            type: 'line'
          }
        ]
      };
      myChart.setOption(option);
    },
  },
  created() {
    this.totalUsers = this.users.length;
  }
};
</script>

<style lang="less" scoped>
.suggest {
  padding: 70px 0px 20px 260px;
  background-color: #F9FAFB;
  width: 100%;

  h2 {
    display: block;
    visibility: visible;
    margin-left: 10px;
  }

  .search-container {
    box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
    border-radius: 10px;
    border: 1px solid #e9e8e8;
    background-color: white;
    position: relative;
    margin: 20px 10px;


    .el-input {
      margin: 20px;
      width: 400px;
    }

    .el-button {
      padding: 10px 15px;
      border-radius: 8px;

      img {
        position: relative;
        top: 2px;
        width: 15px;
        height: 15px;
      }
    }

    .remove {
      background-color: #f13e1f;
      color: white;
      position: absolute;
      top: 18px;
      right: 20px;
    }
  }

  .detail-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    width: 100%;
  }

  .detail-SugMessage {
    width: 90%;
  }

  .detail-item {
    flex: 1;
    margin-right: 10px;
  }

  .detail-label {
    display: block;
    color: rgb(160, 160, 160);
    margin-bottom: 5px;
    font-weight: normal;
  }

  .close-button {
    background-color: #f4f4f4;
    color: #666;
    border: 1px solid #ccc;
  }

  .send-button {
    background-color: #409eff;
    color: white;
    border: none;
  }

  .confirm-button {
    background-color: #27c24c;
    color: white;
    border: none;
  }

  .stats-container {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    margin: 20px 10px;
  }

  .stat-item {
    width: calc(50% - 20px);
    margin-bottom: 20px;
    box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
    border-radius: 10px;
    border: 1px solid #e9e8e8;
    background-color: white;
    border-radius: 5px;
    padding: 20px;
  }

  .stat-item-1 {
    width: calc(25% - 20px);
    margin-bottom: 20px;
    box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
    border-radius: 10px;
    border: 1px solid #e9e8e8;
    background-color: white;
    border-radius: 5px;
    padding: 20px;
  }

  .stat-value {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 10px;
  }

  .stat-change {
    color: green;
  }

  .increase {
    color: green;
  }

  .decrease {
    color: red;
  }

  .stat-tip {
    color: rgb(255, 115, 0);
  }
}
</style>